/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: PostRequestBuilder.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.network.request;

import java.io.File;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

import io.bhex.baselib.network.Encode;
import io.bhex.baselib.network.params.IPostParams;
import io.bhex.baselib.network.params.PostParams;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

public class PostRequestBuilder implements IRequestBuilder<PostParams> {
    private PostParams params;

    public PostRequestBuilder params(PostParams params) {
        this.params = params;
        return this;
    }

    public Request build() {
        RequestBody body =null;
        if (params.files() == null || params.files().isEmpty()) {
            //没有要上传的文件，说明只是单纯地一些表单参数
            FormBody.Builder builder = new FormBody.Builder();

            addParams(builder, params.postParams());

            body = builder.build();
        } else {
            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);
            addParams(builder, params.postParams());

            for (String key : params.files().keySet()) {

                File file = params.files().get(key);

                RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(file.getName())), file);

                builder.addFormDataPart(key, params.files().get(key).getName(), fileBody);
            }

            body = builder.build();
        }

        Request.Builder builder = new Request.Builder()
                .url(params.getUrl())
                .tag(params.getTag())
                .post(body);

        if (params.getCacheControl() != null)
            builder.cacheControl(params.getCacheControl());

        if(params.getHeaders()!=null && params.getHeaders().size() > 0) {
            Iterator<String> keyIterator = params.getHeaders().keySet().iterator();

            while (keyIterator.hasNext()) {
                String key = keyIterator.next();

                builder.addHeader(key, Encode.urlEncode(params.getHeaders().get(key)));
            }
        }


        return builder.build();
    }

    private void addParams(FormBody.Builder builder, Map<String, Object> params) {
        if (params == null)
            return;

        for (String key : params.keySet()) {
            builder.add(key, params.get(key) != null ? params.get(key).toString() : "");
        }
    }

    private void addParams(MultipartBody.Builder builder, Map<String, Object> params) {
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
//                builder.addPart(Headers.of("Content-Disposition", "x-www-form-urlencoded; name=\"" + key + "\""),
                        RequestBody.create(null, params.get(key).toString()));
            }
        }
    }


    private String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }
}
